package com.demo.controller;

import com.demo.model.User;
import com.demo.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @Auther: luobiao
 * @Date: 2020/5/22 07:47
 * @Description:
 */
@RestController
@RequestMapping("user")
public class UserConroller {
    @Autowired
    UserService userService;

    @InitBinder
    public  void initBinder(WebDataBinder binder, HttpServletRequest request){
        binder.registerCustomEditor(Date.class,new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"),false));
    }

    //MyAdvice中设置性别默认值为0表是是woman,controller中设置是man，最终使用的是Advice中的model，因为Advice中优先级更高
    @ModelAttribute
    public User modelAttributeUser(){
        User user =new User();
        user.setSex("man");
        return user;
    }

    //http://localhost:8080/user/add?name=luobiao&age=30&birthday=1991-04-04 2011:12:13
    @RequestMapping("/add")
    public String add(@Validated User user, ModelMap modelMap){
        user.setId(UUID.randomUUID().toString());
        userService.addUser(user);
        return "success";
    }

}
